package test.demo.io;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author Hinsteny
 * @date 2016/5/26
 * @copyright: 2016 All rights reserved.
 */
public class AioClient {

	private String address = "127.0.0.1";
	private int port = 8000;
	
	private final AsynchronousSocketChannel client;

	public AioClient() throws Exception {
		client = AsynchronousSocketChannel.open();
	}

	public void start() throws Exception {
		client.connect(new InetSocketAddress(address, port), null,
			// 建立连接后的回调
			new CompletionHandler<Void, Object>() {
				@Override
				public void completed(Void result, Object attachment) {
					try {
						System.out.println("Connect to channel successed and start send data to server...");
						client.write(ByteBuffer.wrap("Hinsteny is come here ..".getBytes())).get();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}

				@Override
				public void failed(Throwable exc, Object attachment) {
					exc.printStackTrace();
				}
			});
		
		final ByteBuffer bb = ByteBuffer.allocate(1024);
		client.read(bb, null,
			// 读操作结束后的回调
			new CompletionHandler<Integer, Object>() {
				@Override
				public void completed(Integer result, Object attachment) {
					System.out.println("Message size is:" + result);
					System.out.println("Message content is:" + new String(bb.array()));
				}
	
				@Override
				public void failed(Throwable exc, Object attachment) {
					exc.printStackTrace();
				}
			});

		try {
			// Wait for ever
			Thread.sleep(Integer.MAX_VALUE);
		} catch (InterruptedException ex) {
			System.out.println(ex);
		}

	}

	public static void main(String args[]) throws Exception {
		new AioClient().start();
	}
}
